package com.moyu.shiro.config;

import com.moyu.shiro.realm.MyRealm;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyShiroConfiguration {

  @Bean
  public MyRealm myRealm() {
    return new MyRealm();
  }

  @Bean
  public SecurityManager securityManager() {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(myRealm());
    return securityManager;
  }

  @Bean
  public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) {
    ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
    factoryBean.setSecurityManager(securityManager);
    Map<String, String> map = new HashMap<>();
    map.put("/logout", "logout");
    map.put("/css/**", "anon"); // 静态资源放行
    map.put("/js/**", "anon");  // 静态资源放行
    map.put("/**", "authc");
    factoryBean.setLoginUrl("/login");
    factoryBean.setSuccessUrl("/index");
    factoryBean.setUnauthorizedUrl("/error");
    factoryBean.setFilterChainDefinitionMap(map);
    return factoryBean;
  }

  @Bean
  public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(
      SecurityManager securityManager) {
    AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
    advisor.setSecurityManager(securityManager);
    return advisor;
  }
}
